package com.mr.sell.controller;

import com.mr.sell.entity.ProductCategory;
import com.mr.sell.entity.ProductInfo;
import com.mr.sell.service.CategoryService;
import com.mr.sell.service.ProductService;
import com.mr.sell.utils.ResultVOUtil;
import com.mr.sell.vo.ProductVO;
import com.mr.sell.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    /**
    * @user (作者)MRui
    * @Description: TODO描述:
    * @date 2018.09.18 22:09
    */
    @GetMapping("/list")
    public ResultVO list(){
        //1.查询所有上架商品
        List<ProductInfo> productInfoList = productService.getUpAll(0);

        //2.查询类目（一次性查询）
        //List<Integer> categoryTypeList = new ArrayList<>();
        //lambda表达式  将productInfoList先转成stream然后取出CategoryType组成一个list
        List<Integer> categoryTypeList = productInfoList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
        //3.数据拼装
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());
            List<ProductInfo> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo:productInfoList) {
                if (productInfo.getCategoryType()==productCategory.getCategoryType()){
                    ProductInfo productInfoVO = new ProductInfo();
                    //Spring 提供复制工具将productInfo对象复制到productInfoVO里面
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoList(productInfoVOList);
            productVOList.add(productVO);
        }

        ResultVO resultVO = ResultVOUtil.success(productVOList);

        return resultVO;
    }
}
